<script setup>
import { ref } from "vue";
import { useUserStore } from "@/stores/user.js";
import {
  userout,
  userupdate,
  editReferrer,
  setPayPasswordApi,
  resetPasswordByFormerApi,
  resetPasswordBySmsCodeApi,
} from "@/services/setting";
import arrurl from "@/static/index/icom-tx.png";
import { userloginStore } from "@/stores/islogin.js";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { isPayPassApi } from "@/services/user";
import { send } from "@/services/login";
import { getAuthApi } from "@/services/reward";
import { base_URL } from "@/utils/http";
const user = useUserStore();
const userlogin = userloginStore();
const logintype = ref(uni.getStorageSync("loginType"));

// 用户信息数据
const nickname = ref("");
const name = ref("");
const avatar = ref("");
const phone = ref(user.userInfo.phone);
const referrer = ref("");
const showname = ref(false);
const showreferee = ref(false);
const inputname = ref(user.userInfo.nickname);
const inputpassword1 = ref("");
const inputpassword2 = ref("");
const referrer_id = ref("");
onShow(async () => {
  await isPayPassFun();
  await getAuthFun();
  nickname.value = user.userInfo.nickname;
  name.value =
    authObj.value && authObj.value.name
      ? authObj.value.name
      : user.userInfo.name;
  avatar.value = user.userInfo.avatar ? user.userInfo.avatar : arrurl;
  phone.value = user.userInfo.phone;
  valiFormData.value.phone = user.userInfo.phone;
  referrer.value = user.userInfo.referrer;
  referrer_id.value = user.userInfo.referrer_id;
});
onLoad((e) => {
  isshowPassword.value = e.isshowPassword;
  if (isshowPassword.value == 0) {
    showpassword.value = true;
  }
  if (isshowPassword.value == 1) {
    password_code.value = true;
  }
});

const authObj = ref({});
async function getAuthFun() {
  let res = await getAuthApi();
  if (res.code == 200) {
    authObj.value = res.data;
  } else {
    uni.showToast({
      title: res.info,
      icon: "none",
    });
  }
}

if (!user.userInfo.id) {
  // uni.switchTab({
  //     url: '/pages/my/my'
  // });
}

const imageStyles = ref({
  width: 64,
  height: 64,
  border: {
    radius: "50%",
  },
});
// uni.setStorageSync()

//文件上传
const selectFileNew = (e) => {
  uni.showLoading({
    mask: true,
    title: "上传中",
  });

  uni.uploadFile({
    url: base_URL + "/api/upload/file",
    filePath: e.tempFilePaths[0],
    name: "file",
    formData: {
      user: "test",
    },
    header: {
      Authorization: uni.getStorageSync("Authorization"),
    },
    success: async (uploadFileRes) => {
      let data = JSON.parse(uploadFileRes.data);
      if (data.code == 200) {
        avatar.value = data.data.url;
        user.userInfo.avatar = data.data.url;

        let res = await userupdatefun("", data.data.url);
        if (res.code == 200) {
          uni.hideLoading();
          uni.showToast({
            title: "修改成功",
            icon: "none",
          });
        } else {
          avatar.value = user.userInfo.avatar ? user.userInfo.avatar : arrurl;
          uni.hideLoading();
          uni.showToast({
            title: "修改失败,请重试",
            icon: "none",
          });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/my/index",
            });
          }, 1500);
        }
      } else {
        avatar.value = user.userInfo.avatar ? user.userInfo.avatar : arrurl;
        uni.hideLoading();
        uni.showToast({
          title: data.info,
          icon: "none",
        });
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/my/index",
          });
        }, 1500);
      }
    },
    fail: function (e) {
      uni.hideLoading();
      avatar.value;
      uni.showToast({
        title: "上传失败,请重新上传",
        icon: "none",
      });
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/my/index",
        });
      }, 1500);
    },
  });
};

async function userupdatefun(name, images) {
  let dataobj = null;
  if (name) {
    dataobj = {
      nickname: name,
    };
  } else {
    dataobj = { avatar: images };
  }
  let res = await userupdate(dataobj);
  return res;
}

//去修改绑定手机
const gosetupphonefun = () => {
  uni.navigateTo({
    url: "/pages/mysetting/upphone/index",
  });
};

// //修改支付密码
// const gosetuppayfun = () => {
//   if (!name.value) {
//     uni.switchTab({
//       url: "/pages/my/my",
//     });
//     return;
//   }
//   uni.navigateTo({
//     url: "/pages/paypass/index",
//   });
// };

//安全退出
const outlogin = async () => {
  let res = await userout();
  if (res.code === 200) {
    uni.removeStorageSync("userInfo");
    uni.removeStorageSync("jwt-token");
    uni.removeStorageSync("Authorization");
    uni.setStorageSync("outlogin", true);
    user.userInfo = {};
    userlogin.setlogin(false);

    uni.reLaunch({
      url: "/pages/login/login",
    });
  }
};
const gomy = () => {
  showname.value = true;
};

// 去更改推荐人
const goReferee = () => {
  uni.navigateTo({
    url: "/pages/mysetting/reffrrer/index",
  });

  // if (referrer_id.value == 1) {
  //   uni.navigateTo({
  //     url: "/pages/mine/modifySupplier",
  //   });
  // } else {
  //   uni.showToast({
  //     title: "推荐人不是系统，无法修改！",
  //     icon: "none",
  //   });
  //   return;
  // }
};
const close = () => {
  showname.value = false;
  showreferee.value = false;
  showpassword.value = false;
  password_code.value = false;
  valiFormData.value.new_password1 = "";
  valiFormData.value.new_password2 = "";
  valiFormData.value.code = "";
  oldpassword.value = "";
  newpassword1.value = "";
  newpassword2.value = "";
  inputpassword1.value = "";
  inputpassword2.value = "";
  focusinput.value = false;
};

const savenamefun = () => {
  showname.value = false;
  nickname.value = inputname.value;
  userupdatefun(inputname.value, "");
};

const isPayPass = ref(0);
const isPayPassFun = async () => {
  try {
    let res = await isPayPassApi();
    if (res.code == 200) {
      isPayPass.value = res.data;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const showpassword = ref(false);
const password_code = ref(false);
const isshowPassword = ref(3);
const focusinput = ref(false);
const gopassword = () => {
  if (isPayPass.value == 0) {
    showpassword.value = true;
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  } else {
    password_code.value = true;
    setTimeout(() => {
      focusinput.value = true;
    }, 500);
  }
};
const savepasswordfun = async () => {
  if (isPayPass.value == 0) {
    if (!inputpassword1.value || !inputpassword2.value) {
      uni.showToast({
        title: "密码不能为空！",
        icon: "none",
      });
      return;
    }
    if (inputpassword1.value.length != 6 || inputpassword2.value.length != 6) {
      uni.showToast({
        title: "请输入6位数字密码！",
        icon: "none",
      });
      return;
    }
    if (inputpassword1.value != inputpassword2.value) {
      uni.showToast({
        title: "两次密码不一致！",
        icon: "none",
      });
      inputpassword2.value = "";
      return;
    }

    try {
      let res = await setPayPasswordApi({ password: inputpassword1.value });
      if (res.code == 200) {
        uni.showToast({
          title: "设置成功",
          icon: "none",
        });
        showpassword.value = false;
        inputpassword1.value = "";
        inputpassword2.value = "";
        if (isshowPassword.value == 0) {
          setTimeout(() => {
            uni.navigateBack({
              delta: 1, // 返回的页面数
            });
          }, 500);
        }
        isPayPass.value = 1;
      }
    } catch (e) {
      // showpassword.value = false;
      // inputpassword1.value = "";
      // inputpassword2.value = "";
      isPayPass.value = 0;
      uni.showToast({
        title: e.info,
        icon: "none",
      });
    }
  } else {
  }
};

const oldpassword = ref("");
const newpassword1 = ref("");
const newpassword2 = ref("");

const password_codefun = async () => {
  if (isPayPass.value == 1) {
    if (!oldpassword.value || !newpassword1.value || !newpassword2.value) {
      uni.showToast({
        title: "密码不能为空！",
        icon: "none",
      });
      return;
    }
    if (
      oldpassword.value.length != 6 ||
      newpassword1.value.length != 6 ||
      newpassword2.value.length != 6
    ) {
      uni.showToast({
        title: "请输入6位数字密码！",
        icon: "none",
      });
      return;
    }

    if (newpassword1.value != newpassword2.value) {
      uni.showToast({
        title: "两次密码不一致！",
        icon: "none",
      });
      newpassword2.value = "";
      return;
    }
    try {
      let res = await resetPasswordByFormerApi({
        old_password: oldpassword.value,
        new_password: newpassword1.value,
      });
      if (res.code == 200) {
        uni.showToast({
          title: "修改成功",
          icon: "none",
        });
        password_code.value = false;
        oldpassword.value = "";
        newpassword1.value = "";
        newpassword2.value = "";

        if (isshowPassword.value == 1) {
          setTimeout(() => {
            uni.navigateBack({
              delta: 1, // 返回的页面数
            });
          }, 500);
        }
      }
    } catch (e) {
      uni.showToast({
        title: e.info,
        icon: "none",
      });
      // oldpassword.value = "";
      // newpassword1.value = "";
      // newpassword2.value = "";
    }
  }
};

const inputfun = (val) => {
  if (val.length >= 6) {
    uni.showToast({
      title: "内容过长",
      icon: "none",
    });
  }
};

const radiovalue1 = ref("原密码");
// 基本案列数据
const radiolist1 = ref([
  {
    name: "原密码",
    disabled: false,
  },
  {
    name: "手机验证码",
    disabled: false,
  },
]);

const update_type = ref(0);
const radioChange = (index) => {
  update_type.value = index;
};
const valiFormData = ref({
  phone: phone.value,
  code: "",
});
const valiForm = ref(null);
const timenum = ref(60);
let timeget = null;
const codedisabled = ref(false);
/* 手机号校验规则*/
const formRules = ref({
  phone: {
    rules: [
      {
        required: true,
        errorMessage: "手机号不能为空",
      },
      {
        validateFunction: function (rule, value, data, callback) {
          let iphoneReg = /^1\d{10}$/; //手机号码
          if (!iphoneReg.test(value)) {
            ts(1);
            callback("手机号码格式不正确，请重新填写");
          }
        },
      },
    ],
  },

  code: {
    rules: [
      {
        required: true,
        errorMessage: "手机验证码不能为空",
      },
    ],
  },
});

/* 发送手机号 */
const getcodes = async () => {
  if (!valiFormData.value.phone.length) {
    uni.showToast({
      title: "手机号码不能为空！",
      icon: "none",
    });
    return;
  }
  if (valiFormData.value.phone.length != 11) {
    uni.showToast({
      title: "手机号码格式不正确！",
      icon: "none",
    });
    return;
  }

  if (codedisabled.value) {
    return;
  }
  valiForm.value
    .validateField(["phone"])
    .then(async (ress) => {
      codedisabled.value = true;

      timeget = setInterval(function () {
        timenum.value--;
        if (timenum.value <= 0) {
          codedisabled.value = false;
          clearInterval(timeget);
          timenum.value = 60;
        }
      }, 1000);
      const res = await send({
        phone: valiFormData.value.phone,
      });
      if (res.code == 200) {
        uni.showToast({
          title: "发送成功",
          icon: "none",
        });
      } else {
        uni.showToast({
          title: res.info,
          icon: "none",
        });
      }
    })
    .catch((e) => {
      uni.showToast({
        title: e.info,
        icon: "none",
      });
    });
};
const phone_codefun = async () => {
  if (isPayPass.value == 1) {
    if (!valiFormData.value.phone.length) {
      uni.showToast({
        title: "手机号码不能为空！",
        icon: "none",
      });
      return;
    }
    if (valiFormData.value.phone.length != 11) {
      uni.showToast({
        title: "手机号码格式不正确！",
        icon: "none",
      });
      return;
    }
    if (
      !valiFormData.value.new_password1 ||
      !valiFormData.value.new_password2
    ) {
      uni.showToast({
        title: "新密码不能为空！",
        icon: "none",
      });
      return;
    }
    if (
      valiFormData.value.new_password1.length != 6 ||
      valiFormData.value.new_password2.length != 6
    ) {
      uni.showToast({
        title: "请输入6位数字密码！",
        icon: "none",
      });
      return;
    }
    if (!valiFormData.value.code) {
      uni.showToast({
        title: "验证码不能为空！",
        icon: "none",
      });
      return;
    }

    if (valiFormData.value.new_password1 != valiFormData.value.new_password2) {
      uni.showToast({
        title: "两次密码不一致！",
        icon: "none",
      });
      valiFormData.value.new_password2 = "";
      return;
    }
    try {
      let res = await resetPasswordBySmsCodeApi({
        phone: valiFormData.value.phone,
        code: valiFormData.value.code,
        new_password: valiFormData.value.new_password1,
      });
      if (res.code == 200) {
        uni.showToast({
          title: "修改成功",
          icon: "none",
        });
        valiFormData.value.code = "";
        valiFormData.value.new_password1 = "";
        valiFormData.value.new_password2 = "";
        password_code.value = false;

        if (isshowPassword.value == 1) {
          setTimeout(() => {
            uni.navigateBack({
              delta: 1, // 返回的页面数
            });
          }, 500);
        }
      }
    } catch (e) {
      uni.showToast({
        title: e.info,
        icon: "none",
      });
      // valiFormData.value.code = "";
      // valiFormData.value.new_password1 = "";
      // valiFormData.value.new_password2 = "";
    }
  }
};

const inputnew_password1 = (e) => {
  console.log(e);
  if (e.includes(" ") || isNaN(e)) {
    setTimeout(() => {
      valiFormData.value.new_password1 = "";
      uni.showToast({
        title: "密码格式错误，请6位数字密码！",
        icon: "none",
      });
    }, 100);
  }
};
const inputnew_password2 = (e) => {
  if (e.includes(" ") || isNaN(e)) {
    setTimeout(() => {
      valiFormData.value.new_password2 = "";
      uni.showToast({
        title: "密码格式错误，请6位数字密码！",
        icon: "none",
      });
    }, 100);
  }
};
const onChangeinputpassword = (e) => {
  if (e) {
  }
};
const onChange = (e) => {};
</script>

<template>
  <view class="changePhone">
    <!-- <view class="block"></view> -->
    <view class="changePhone-card">
      <view class="example-body custom-image-box">
        <text class="text">头像</text>

        <uni-file-picker
          limit="1"
          :del-icon="false"
          disable-preview
          :imageStyles="imageStyles"
          :auto-upload="false"
          @select="selectFileNew"
          sizeType="['compressed']"
          file-mediatype="image"
        >
          <image class="setting-avatar" :src="avatar" mode="aspectFill"></image>
        </uni-file-picker>
      </view>
      <view class="list-item" @click="goReferee">
        <view class="list-item-left"> 推荐人 </view>
        <view class="list-item-right">
          <text>{{ referrer ? referrer.nickname : "去添加推荐人" }}</text>
          <image
            src="@/pages/mysetting/static/login/common_more_gray.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
      <view class="list-item" @click="gomy">
        <view class="list-item-left"> 昵称 </view>
        <view class="list-item-right">
          <text>{{ nickname ? nickname : "---" }}</text>
          <image
            src="@/pages/mysetting/static/login/common_more_gray.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
      <view class="list-item">
        <view class="list-item-left"> 姓名 </view>
        <view class="list-item-right">
          {{ name ? name : "---" }}
        </view>
      </view>
      <view class="list-item" @click="gosetupphonefun">
        <view class="list-item-left"> 手机号 </view>
        <view class="list-item-right">
          <text>{{ phone ? phone : "去添加手机号" }}</text>
          <image
            src="@/pages/mysetting/static/login/common_more_gray.png"
            mode="widthFix"
          ></image>
        </view>
      </view>

      <view class="list-item" @click="gopassword">
        <view class="list-item-left"> 支付密码 </view>
        <view class="list-item-right">
          <text>{{ isPayPass == 0 ? "去设置支付密码" : "******" }}</text>
          <image
            src="@/pages/mysetting/static/login/common_more_gray.png"
            mode="widthFix"
          ></image>
        </view>
      </view>

      <!-- <button class="btn">
				<text class="btn-text">确定修改</text>
			</button> -->
    </view>
    <view class="loginout" @click="outlogin">
      <view class="loginout-bt"> 退出登录 </view>
    </view>
  </view>

  <view class="password_show">
    <up-popup
      :show="showname"
      mode="center"
      :round="10"
      @close="close"
      @open="open"
    >
      <view>
        <view class="form-index">
          <up-form
            labelPosition="left"
            :model="model1"
            :rules="rules"
            ref="form1"
          >
            <view class="inputname-item">
              <up-form-item label="昵称:" borderBottom ref="item1">
                <view class="inputname">
                  <up-input
                    v-model="inputname"
                    placeholder="请输入昵称"
                    maxlength="6"
                    @input="inputfun"
                  ></up-input>
                </view>
              </up-form-item>
            </view>
          </up-form>
          <view class="loginout" @click="savenamefun">
            <view class="loginout-bt"> 保存 </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>

  <view class="password_show">
    <up-popup
      :show="showpassword"
      mode="center"
      :round="10"
      @close="close"
      @open="open"
    >
      <view>
        <view class="form-index">
          <up-form
            labelPosition="left"
            :model="model1"
            :rules="rules"
            ref="form1"
          >
            <up-form-item label="输入支付密码：" borderBottom ref="item1">
              <view class="imfrom-k">
                <u-code-input
                  v-model="inputpassword1"
                  :maxlength="6"
                  dot
                  :space="0"
                  @change="onChangeinputpassword"
                  @finish="finish"
                  :focus="focusinput"
                ></u-code-input>
              </view>
            </up-form-item>
            <up-form-item label="确认支付密码：" borderBottom ref="item1">
              <view class="imfrom-k">
                <u-code-input
                  v-model="inputpassword2"
                  :maxlength="6"
                  dot
                  :space="0"
                  @change="onChange"
                  @finish="finish"
                ></u-code-input>
              </view>
            </up-form-item>
          </up-form>
          <view class="loginout" @click="savepasswordfun">
            <view class="loginout-bt"> 保存 </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>

  <view class="password_show">
    <up-popup
      :show="password_code"
      mode="center"
      :round="10"
      @close="close"
      @open="open"
    >
      <view :class="update_type == 0 ? 'password_radio' : 'password_radio1'">
        <up-radio-group v-model="radiovalue1" placement="row">
          修改方式：
          <up-radio
            :customStyle="{ margin: '8px' }"
            v-for="(item, index) in radiolist1"
            :key="index"
            :label="item.name"
            :name="item.name"
            @change="radioChange(index)"
            activeColor="#f3498b"
          >
          </up-radio>
        </up-radio-group>
      </view>
      <view v-if="update_type == 0">
        <view class="form-index">
          <up-form
            labelPosition="left"
            :model="model1"
            :rules="rules"
            ref="form1"
          >
            <up-form-item label="原支付密码：" borderBottom ref="item1">
              <view class="imfrom-k">
                <u-code-input
                  v-model="oldpassword"
                  :maxlength="6"
                  dot
                  :space="0"
                  @change="onChange"
                  @finish="finish"
                  required
                  :focus="focusinput"
                ></u-code-input>
              </view>
            </up-form-item>

            <up-form-item label="新支付密码：" borderBottom ref="item1">
              <view class="imfrom-k">
                <u-code-input
                  v-model="newpassword1"
                  :maxlength="6"
                  dot
                  :space="0"
                  @change="onChange"
                  @finish="finish"
                  required
                ></u-code-input>
              </view>
            </up-form-item>
            <up-form-item label="确认新密码：" borderBottom ref="item1">
              <view class="imfrom-k">
                <u-code-input
                  v-model="newpassword2"
                  :maxlength="6"
                  dot
                  :space="0"
                  @change="onChange"
                  @finish="finish"
                  required
                ></u-code-input>
              </view>
            </up-form-item>
          </up-form>
          <view class="loginout" @click="password_codefun">
            <view class="loginout-bt"> 保存 </view>
          </view>
        </view>
      </view>
      <view v-if="update_type == 1">
        <view class="form-index">
          <view class="form-k">
            <uni-forms
              ref="valiForm"
              :rules="formRules"
              :modelValue="valiFormData"
              label-width="80"
            >
              <view class="imfrom-k">
                <view class="imfrom-k-icon">
                  <image src="@/static/login/login_phone.png" mode="widthFix" />
                </view>
                <uni-forms-item label="" name="phone">
                  <uni-easyinput
                    v-model="valiFormData.phone"
                    placeholder="请输入手机号码"
                    disabled
                  />
                </uni-forms-item>
              </view>
              <view class="imfrom-k">
                <view class="imfrom-k-icon">
                  <image src="@/static/login/login_code.png" mode="widthFix" />
                </view>
                <uni-forms-item label="" name="new_password">
                  <up-input
                    v-model="valiFormData.new_password1"
                    placeholder="请输入新密码"
                    type="number"
                    password
                    required
                    :maxlength="6"
                    :minlength="6"
                    :passwordToggle="true"
                    @change="inputnew_password1"
                  />
                </uni-forms-item>
              </view>

              <view class="imfrom-k">
                <view class="imfrom-k-icon">
                  <image src="@/static/login/login_code.png" mode="widthFix" />
                </view>
                <uni-forms-item label="" name="new_password">
                  <up-input
                    v-model="valiFormData.new_password2"
                    placeholder="请确认新密码"
                    type="number"
                    password
                    required
                    :maxlength="6"
                    :minlength="6"
                    :passwordToggle="true"
                    @change="inputnew_password2"
                  />
                </uni-forms-item>
              </view>

              <view class="imfrom-k">
                <view class="imfrom-k-icon">
                  <image src="@/static/login/login_code.png" mode="widthFix" />
                </view>
                <uni-forms-item label="" name="code">
                  <view class="imfrom-k-yz">
                    <view class="imfrom-inputs">
                      <uni-easyinput
                        v-model="valiFormData.code"
                        placeholder="请输入验证码"
                      >
                        <template #right>
                          <view
                            :class="
                              valiFormData.phone ? 'getcodes1' : 'getcodes'
                            "
                            @click="getcodes"
                          >
                            <text :class="codedisabled ? 'selectcodes' : ''">{{
                              codedisabled
                                ? timenum + "s后重新获取"
                                : "获取验证码"
                            }}</text>
                          </view>
                        </template>
                      </uni-easyinput>
                    </view>
                  </view>
                </uni-forms-item>
              </view>
            </uni-forms>
          </view>
          <view class="loginout" @click="phone_codefun">
            <view class="loginout-bt"> 保存 </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
